﻿using Abp.Events.Bus.Handlers;
using Abp.Runtime.Caching;
using NetCore.Events;
using System.Threading.Tasks;

namespace NetCore.EventHandlers
{
    /// <summary>
    /// 异步或同步移除缓存的全局HandlerAbp 在底层会扫描实现了IEventHandler或IAsyncEventHandler
    /// 这两个接口的类型，将其自动注册为订阅者
    /// </summary>
    public class RemoveCacheEventHandler : IAsyncEventHandler<RemoveCacheEvent>, IEventHandler<RemoveCacheEvent>//, ITransientDependency
    {
        private readonly ICacheManager _cacheManager;

        /// <inheritdoc />
        public RemoveCacheEventHandler(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 异步方法
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        public async Task HandleEventAsync(RemoveCacheEvent eventData)
        {
            var cache = _cacheManager.GetCache(eventData.CacheName);
            if (cache is null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(eventData.Key))
            {
                await cache.ClearAsync();
            }
            else
            {
                await cache.RemoveAsync(eventData.Key);
            }
        }
        /// <summary>
        /// 同步方法
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(RemoveCacheEvent eventData)
        {
            var cache = _cacheManager.GetCache(eventData.CacheName);
            if (cache is null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(eventData.Key))
            {
                cache.Clear();
            }
            else
            {
                cache.Remove(eventData.Key);
            }
        }
    }
}
